package command;

import object.*;
import utils.FileCreation;
import utils.FileDeletion;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class ResetCommand {
    private String mode;
    private String id;
    public ResetCommand(String mode, String id){
        this.mode = mode;
        this.id = id;
    }
    public void excute() throws Exception{
        if("--soft".equals(this.mode)){
            HEAD head = HEAD.deserialize();
            Commit commit = Commit.deserialize(this.id);
            head.updateHEAD(commit);
            head.writeObject();
        }
        else if("--mixed".equals(this.mode)){
            Stage stage = Stage.deserialize();
            stage.clearStage();
            stage.writeObject();
        }
        else if("--hard".equals(this.mode)){
            // Delete the original files
            File file = new File(".");
            for( File fs : file.listFiles()){
                if( !fs.getName().equals(".jit") ){
                    FileDeletion.deleteFile(fs);
                }
            }

            Stage stage = Stage.deserialize();
            HashMap<String, String[]> addedFiles = stage.getAddedFiles();
            Iterator iter = addedFiles.entrySet().iterator();
            while(iter.hasNext() ){
                Map.Entry entry = (Map.Entry) iter.next();
                String path = (String)entry.getKey();
                String[] info = (String[])entry.getValue();
                if("Tree".equals(info[0])){
                    Tree tree = Tree.deserialize(info[1]);
                    FileCreation.createDirectory(".", tree.getPath());
                }
                else if("Blob".equals(info[0])){
                    Blob blob = Blob.deserialize(info[1]);
                    FileCreation.createFile(".", blob.getPath(), blob.getContent());
                }
            }
        }
    }
}
